package org.andy.json;

import java.util.Map;
import java.util.HashMap;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class AjaxServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        String processData = request.getParameter("processData");

        response.setContentType("application/json");
        response.setHeader("Cache-Control", "no-cache");

        Map<String, String> personMap = new HashMap<String, String>();

        if (processData != null && processData.equalsIgnoreCase("JSON")) {
            personMap.put("processData", processData);
            personMap.put("firstName", "Java");
            personMap.put("lastName", "Honk");
        } else {
            for (int i = 0; i < 5; i++) {
                personMap.put("firstName" + i, "Java");
                personMap.put("lastName"  + i, "Honk");
            }
        }

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(personMap);
        response.getWriter().write(json);
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    }
}
